package data

import (
	"math/rand"

	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/client/chain"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/core/config"
)

type BaasEnv struct {
	orgName string
	iamId   string
	chainId string

	cert string
	pvk  string

	tlsCert string
	tlsKey  string

	adminCert string
	adminPvk  string
	loglevel  string

	inodeList  []string
	inodeUrls  []string
	inodeCerts []string

	consenserList  []string
	consenserUrls  []string
	consenserCerts []string

	ccInvoke   []chain.Request
	cryptoType string
}

func (b *BaasEnv) ChainId() string {
	return b.chainId
}

func (b *BaasEnv) SdkBuilder() *config.Builder {
	// 初始化客户端配置
	cli := config.NewClient().SetOrg(b.orgName).SetLogLevel(b.loglevel).SetBCCSP(b.cryptoType, "", 0).
		SetTlsClient(config.NewCredential().SetPem(b.tlsCert), config.NewCredential().SetPem(b.tlsKey))
	// 初始化组织配置
	orgs := config.NewOrgs().AddOrg(b.orgName, config.NewOrg().SetIAMId(b.iamId).SetCryptoPath("./").SetInode(b.inodeList))
	// 初始化链配置
	chains := config.NewChains().AddChain(b.chainId, b.consenserList, b.inodeList)
	// 初始化共识节点配置
	consensers := config.NewConsensers()
	for i, consenser := range b.consenserList {
		var cert *config.Credential
		if len(b.consenserCerts) > 0 {
			cert = config.NewCredential().SetPem(b.consenserCerts[i])
		}
		consensers.AddConsenser(consenser, b.consenserUrls[i], cert)
	}
	// 初始化inode节点配置
	inodes := config.NewInodes()
	for i, inode := range b.inodeList {
		var cert *config.Credential
		if len(b.consenserCerts) > 0 {
			cert = config.NewCredential().SetPem(b.inodeCerts[i])
		}
		inodes.AddInode(inode, b.inodeUrls[i], cert)
	}
	builder := config.NewBuilder().SetClient(cli).SetOrgs(orgs).SetChains(chains).SetConsensers(consensers).SetInodes(inodes)
	return builder
}

func (b *BaasEnv) ClientCert() []byte {
	return []byte(b.cert)
}

func (b *BaasEnv) ClientPvk() []byte {
	return []byte(b.pvk)
}

func (b *BaasEnv) RandInvokeFunc() chain.Request {
	if len(b.ccInvoke) == 0 {
		return chain.Request{}
	}
	index := rand.Intn(len(b.ccInvoke))
	return b.ccInvoke[index]
}

func (b *BaasEnv) RandInodeName() string {
	if len(b.inodeList) == 0 {
		return ""
	}
	index := rand.Intn(len(b.inodeList))
	return b.inodeList[index]
}

func (b *BaasEnv) AdminCert() []byte {
	return []byte(b.adminCert)
}

func (b *BaasEnv) AdminKey() []byte {
	return []byte(b.adminPvk)
}
